<template>
  <!-- 物联网充值列表 -->
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <div class="curd-foter">
          <div class="redFontBox">缴费笔数：<span class="redFont">{{ exhibition(countData.totalPayNum) || 0}}</span> 笔</div>
          <div class="redFontBox">缴费金额：<span class="redFont">{{ exhibition(countData.totalPayAmt ) || 0 }}</span> 元</div>
        </div>
      </template>
      <template slot="menuRight">
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          v-if="row.orderStatus === 1"
          icon="el-icon-s-check"
          size="small"
          type="text"
          @click.stop="clickRefund(row)"
          >退 款</el-button
        >
      </template>
      <!--  -->
      <template slot-scope="{disabled,size}" slot="payDateStartSearch">
        <el-date-picker v-model="search.payDateStart" type="datetime" value-format='yyyy-MM-dd HH:mm:ss' @change="beginTimeChange" placeholder="请输入 交易开始日期"></el-date-picker>
      </template>
      <template slot-scope="{disabled,size}" slot="payDateEndSearch">
        <el-date-picker v-model="search.payDateEnd" type="datetime" default-time="23:59:59" value-format='yyyy-MM-dd HH:mm:ss' @change="endTimeChange" placeholder="请输入 交易结束日期"></el-date-picker>
      </template>
    </avue-crud>
    <el-dialog
      title="退款"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogRefundVisible"
      :before-close="handleCloseRefundForm"
    >
      <avue-form ref="serveForm" :option="refundOption" v-model="refundForm" @submit="refundSubmit"></avue-form>
    </el-dialog>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form :model="towPwdForm" ref="towPwdForm" label-width="0" class="demo-ruleForm">
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            { required: true,message: '二级密码不能为空', trigger: ['blur','change']},
            { pattern: /^[0-9]{6}$/, message: '二级密码由6位数字组成', trigger: ['blur','change']}
          ]"
          >
          <el-input show-password v-model.number="towPwdForm.towPwd" autocomplete="off" placeholder="输入二级密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList,getListCount,getExport,refundOrder } from "@/api/rb-oem/iot/recharge";
import { mapGetters } from "vuex";
import { downloadFileExcel } from "@/util/util";
import { userHasInfo } from "@/api/rb-oem/forgetPassword/forgetPassword";
import md5 from 'js-md5';

// import { getToken } from "@/util/auth";
// import { dateFormat } from "@/util/date";

export default {
  components: {},
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        menuWidth: 150, //操作栏宽度
        emptyBtnText:'重置',
        // searchIcon:true,
        // searchIndex:3,
        column: [
           {
            label: "物联网卡号",
            prop: "msisdn",
            type: "input",
            width:180,
            search: true,
            overHidden:true
          },
          
          {
            label: "ICCID编号",
            prop: "iccid",
            type: 'input',
            search: true,
            width:180,
            overHidden:true
          },
          {
            label: "缴费类型",
            prop: "rechargeType",
            type: "select",
            search: true,
            hide:true,
            display:false,
            dicData: [{
              label: '充值',
              value: 1
            }, {
              label: '续费',
              value: 2
            }]
          },
          {
            label: "缴费类型",
            prop: "rechargeTypeName",
          },
          {
            label: "缴费日期",
            prop: "payDate",
            type: "input",
            width:140,
            overHidden:true
          },
          {
            label: "套餐类型",
            prop: "productName",
            type: "input"
          },
          {
            label: "缴费周期(年)",
            prop: "paymentCycle",
            width:92,
            type: "input"
          },
          {
            label: "订单金额",
            prop: "totalAmt",
            type: "input"
          },
          {
            label: "订单编号",
            prop: "outTradeNo",
            width:180,
            type: "input",
            search: true
          },
          {
            label: "付款方式",
            prop: "payWay",
            type: "select",
            search: true,
            hide:true,
            display:false,
            dicData: [{
              label: '微信',
              value: 1
            }, {
              label: '支付宝',
              value: 2
            }, {
              label: '云闪付',
              value: 3
            }]
          },
          {
            label: "付款方式",
            prop: "payWayName",
          },
          {
            label: "订单状态",
            prop: "orderStatus",
            type: "select",
            search: true,
            hide:true,
            display:false,
            dicData: [{
              label: '待处理',
              value: 0
            }, {
              label: '交易成功',
              value: 1
            }, {
              label: '退款成功',
              value: 2
            }]
          },
          {
            label: "订单状态",
            prop: "orderStatusName",
          },
          {
            label: "充值状态",
            prop: "orderRechargeStatus",
            type: "select",
            search: true,
            hide:true,
            display:false,
            dicData: [{
              label: '待处理',
              value: 0
            }, {
              label: '充值成功',
              value: 1
            }, {
              label: '充值失败',
              value: 2
            }]
          },
          {
            label: "充值状态",
            prop: "orderRechargeStatusName",
          },
          {
            label: "交易ID",
            prop: "openId",
            type: "input",
            width:250,
            search: true
          },
          {
            label: "缴费开始日期",
            prop: "payDateStart",
            search: true,
            hide: true,
            display: false
          },
          {
            label: "缴费结束日期",
            prop: "payDateEnd",
            search: true,
            hide: true,
            display: false
          }
        ]
      },
      data: [],
      countData: {},
      dialogRefundVisible: false, //退款 dialog
      refundOption: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        emptyBtn:false,
        column: [
           {
            label: "退款金额",
            prop: "refundAmount",
            type: "input",
            disabled:true,
            append: '元'
          },
          {
            label: "退款备注",
            prop: "refundRemark",
            type: "textarea",
            span: 24,
            minRows: 2,
            rules: [
              {
                required: true,
                message: "请输入退款理由",
                trigger: "blur",
              },
            ],
          },
        ]
      },
      refundForm: {},
      hasPayPwd:false,
      towPwdForm:{
        towPwd:''
      },
      twoPwdShow:false,
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.iot_recharge_view, false),
        exportBtn: this.vaildData(this.permission.iot_recharge_export, false),
      };
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  watch: {},
  created(){
    this.hasInfo();
  },
  methods: {
    handleCloseRefundForm(done){
      // this.towPwdForm.towPwd="";
      this.$refs.serveForm.resetForm();
      done()
    },
    // 二级密码 关闭回调
    handleCloseTwoPwd(done){
      this.towPwdForm.towPwd="";
      done()
    },
    // 二级密码 确定
    twoPwdSubmit(){
      let _that = this;
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          // let param ={
          //   rptOrderNo:this.refundForm.rptOrderNo,
          //   refundRemark:this.refundForm.refundRemark,
          //   payPwd:md5(this.towPwdForm.towPwd+'')
          // }

          const formData = new FormData();
          formData.append('rptOrderNo', this.refundForm.rptOrderNo);
          formData.append('refundRemark', this.refundForm.refundRemark);
          formData.append('payPwd', md5(this.towPwdForm.towPwd+''));
            
          refundOrder(formData).then(() => {
            _that.twoPwdShow = false;
            _that.towPwdForm.towPwd="";
            _that.dialogRefundVisible = false;
            _that.$message({
              type: "success",
              message: "退款成功!"
            });
            _that.$refs.serveForm.resetForm();
            _that.onLoad(this.page);
          },(error) => {
            window.console.log(error);
          });
        } else {
          return false;
         }
      });
    },
    clickRefund(row){
      this.refundForm.refundAmount = row.totalAmt;
      this.refundForm.rptOrderNo = row.rptOrderNo;
      this.dialogRefundVisible = true;
    },
    /* 提交 退款金额 */
    refundSubmit(row, done) {
      if(this.hasPayPwd){
        this.twoPwdShow=true;
        done();
      } else {
        this.$confirm('请您先设置二级密码，再操作！', '提示', {
          confirmButtonText: '确定',
          showCancelButton:false,
          type: 'warning'
        }).then(() => {
          this.$router.push({ path: '/info/index', query: { index: 2 }})
        })
      }
    },
    hasInfo(){
      userHasInfo().then(res =>{
        this.hasPayPwd = res.data.data.hasPayPwd;
      }, error => {
        window.console.log(error);
      })
    },
    handleExport() {
      let params ={
        ...this.search,
        current:'-1',
        size:'-1'
      }

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(params).then((res) => {
            downloadFileExcel(res);
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    beginTimeChange() {
      if(this.search.payDateEnd){
        if(Date.parse(this.search.payDateStart) > Date.parse(this.search.payDateEnd)){
          this.$alert('缴费开始日期不能大于结束日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.payDateStart = ""))
          .catch(() => (this.search.payDateStart = ""))
        }
      }
    },
    endTimeChange() {
      if(this.search.payDateStart){
        if(Date.parse(this.search.payDateEnd) < Date.parse(this.search.payDateStart)){
          this.$alert('缴费结束日期不能小于开始日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.payDateEnd = ""))
          .catch(() => (this.search.payDateEnd = ""))
        }
      }
    },
    forInSearch(){
      for(let key in this.search){
        if(this.search[key]){
          if(key.indexOf("$") == -1 ){
            this.query[key] = this.search[key]
          }
        }
      }
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      /**
       * @func 统计
       * @desc 根据条件获取统计
       * */
      getListCount(Object.assign(params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then((res) => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
  .redFontBox {
    margin-right: 40px;
    .redFont {
      color: red;
    }
  }
}

/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
</style>
